
var fs = require('fs');
var cmdutils = require('../utils/cmdutils');
var fmt = require('util').format;
var _ = require('underscore');

var _PID_STAT_FILE = '/proc/%d/stat';

exports.processDetect = function(pidFileOrFinder){
  var r = {
    die: true
  };

  var pid = 0;

  if(_.isFunction(pidFileOrFinder)){
    pid = pidFileOrFinder();
  }else{
    if(fs.existsSync(pidFileOrFinder) && fs.statSync(pidFileOrFinder).isFile()){
      pid = parseInt(fs.readFileSync(pidFileOrFinder).toString().trim());
    }
  }



  if(!pid){
    console.error('not found pid by finder');
    return r;
  }else{
    var pidProcFile = fmt(_PID_STAT_FILE, pid);
    if(fs.existsSync(pidProcFile) && fs.statSync(pidProcFile).isFile()){
      var ra = fs.readFileSync(pidProcFile).toString().trim().split(' ');

      var info = {
        pid: pid,
        cmd: ra[1].trim(),
        state: ra[2].trim(),
        ppid: ra[3].trim()
      };
      r.die = false;
      r.info = info;
    }      
  }




  return r;

};